package com.example.solrdemo.config;

import com.example.solrdemo.prop.SolrProperties;
import io.netty.util.internal.StringUtil;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.repository.config.EnableSolrRepositories;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author benjamin_5
 * @Description
 * @date 2023/6/11
 */
@Configuration
public class SolrConfig {

    @Resource
    private SolrProperties solrProperties;

    @Value("${spring.data.solr.host}")
    private String host;

    @Value("${solr.zk.host}")
    private String zkHost;

    @Bean
    public HttpSolrClient httpSolrClient(){
        return new HttpSolrClient.Builder(solrProperties.getHost())
                .withConnectionTimeout(solrProperties.getConnectionTimeout())
                .withSocketTimeout(solrProperties.getSocketTimeout())
                .build();
    }

    @Bean
    public SolrClient solrClient(){
        return new HttpSolrClient.Builder(host).build();
    }

    @Bean
    public SolrTemplate solrTemplate(){
        return new SolrTemplate(solrClient());
    }

    @Bean
    public CloudSolrClient cloudSolrClient(){
        if(StringUtils.isEmpty(zkHost)){
            return null;
        }
        return new CloudSolrClient.Builder(Arrays.asList(zkHost.split(",")))
                .build();
    }
}
